<template>
  <div class="system-user-container layout-padding">
    <el-card shadow="hover" class="layout-padding-auto">
      <div class="system-user-search mb15">
        <el-input size="default" v-model="state.tableData.param.keyword" placeholder="请输入名称"
                  style="max-width: 180px"></el-input>
        <el-button size="default" type="primary" class="ml10" @click="fetchData()">
          <el-icon>
            <ele-Search/>
          </el-icon>
          查询
        </el-button>
        <el-button size="default" type="success" class="ml10" @click="onOpenAddOrEdit('add')">
          <el-icon>
            <ele-FolderAdd/>
          </el-icon>
          新增
        </el-button>
      </div>
      <el-table :data="state.tableData.data" v-loading="state.tableData.loading" style="width: 100%">
        <el-table-column type="index" label="序号" width="50"/>
        <el-table-column prop="driverName" label="驾驶员" width="120px"></el-table-column>
        <el-table-column prop="vehicleNumber" label="车辆号牌" width="150px"></el-table-column>
        <el-table-column prop="signSerialNumber" label="标志牌顺序号" width="110px"></el-table-column>
        <el-table-column prop="reserved1" label="企业签发人" width="120px"></el-table-column>
        <el-table-column prop="viaLocation" label="途经地" width="460px"></el-table-column>
        <el-table-column prop="startLocation" label="起始地" width="100px"></el-table-column>
        <el-table-column prop="endLocation" label="终到地" width="100px"></el-table-column>
        <el-table-column prop="transportCompany" label="运输企业" show-overflow-tooltip width="220px"></el-table-column>
        <el-table-column prop="validStart" label="有效期起" :formatter="dateFormatter" width="150px"></el-table-column>
        <el-table-column prop="validEnd" label="有效期止" :formatter="dateFormatter" width="150px"></el-table-column>
        <el-table-column label="操作" width="380" fixed="right">
          <template #default="scope">
            <el-button size="small" text type="primary" @click="getQrCodeUrlSee(scope.row)">生成二维码</el-button>
            <el-button size="small" text type="primary" @click="downloadPDF(scope.row)">下载电子凭证</el-button>
            <el-button size="small" text type="primary" @click="onOpenAddOrEdit('edit', scope.row)">修改</el-button>
            <el-button size="small" text type="primary" @click="onRowDel(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          class="mt15"
          :pager-count="5"
          :page-sizes="[10, 20, 30]"
          :current-page="state.tableData.param.current"
          background
          :page-size="state.tableData.param.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="state.tableData.total"
      >
      </el-pagination>
    </el-card>

    <div id="pdf-template" style="position: absolute; left: -9999px; top: 0; width: 210mm; height: 297mm; padding: 40px; font-family: 'SimSun', '宋体', 'STSong', serif !important; box-sizing: border-box;">
      <!-- 移除水印元素 -->

      <!-- 双层边框 -->
      <div class="outer-border" style="border: 1px solid #000; padding: 5px; height: 100%; box-sizing: border-box; position: relative;">
        <div class="inner-border" style="border: 1px solid #000; padding: 35px; height: 100%; box-sizing: border-box;">
          <!-- 标题 -->
          <h2 id="title" style="text-align: center; margin-bottom: 40px; font-size: 48px; margin-top: 30px;">省内包车电子凭证</h2>

          <!-- 内容区域 -->
          <div style="line-height: 2.2; margin-left: 30px;">
            <p id="font-size">包车标志牌编号: {{ pdfData.signSerialNumber }}</p>
            <p id="font-size">起始地名称: {{ pdfData.startLocation }}</p>
            <p id="font-size">终点地名称: {{ pdfData.endLocation }}</p>
            <p id="font-size">主 要 途 经 地: {{ pdfData.viaLocation }}</p>
            <p id="font-size">车 牌 号:{{ pdfData.vehicleNumber }}</p>
            <p id="font-size">驾 驶 员:{{ pdfData.driverName }}</p>
            <p id="font-size">运输企业(名称): {{ pdfData.transportCompany }}</p>
            <p id="font-size">企 业 签 发 人:{{ pdfData.reserved1 }}</p>
            <p id="font-size">有 效 期:{{ formatValidDate(pdfData.validStart) }} 至 {{ formatValidDate(pdfData.validEnd) }}</p>
          </div>

          <!-- 二维码 -->
          <div style="position: absolute; bottom: 120px; right: 80px;">
            <img :src="pdfData.qrCode" style="width: 250px; height: 250px;" v-if="pdfData.qrCode" />
          </div>
        </div>
      </div>
    </div>
    <!-- 原有对话框内容保持不变 -->
    <el-dialog :title="state.dialog.title" :visible.sync="state.dialog.isShowDialog" width="70%">
      <div>
        <el-form ref="userDialogFormRef" :model="state.ruleForm" size="default" label-width="120px">
          <el-row :gutter="35">
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
              <el-form-item label="驾驶员">
                <el-input v-model="state.ruleForm.driverName" placeholder="驾驶员" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
              <el-form-item label="车辆号牌">
                <el-input v-model="state.ruleForm.vehicleNumber" placeholder="车辆号牌" clearable></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="35">
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
              <el-form-item label="起始地">
                <el-input v-model="state.ruleForm.startLocation" placeholder="起始地" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
              <el-form-item label="终到地">
                <el-input v-model="state.ruleForm.endLocation" placeholder="终到地" clearable></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="35">
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
              <el-form-item label="有效期起">
                <el-date-picker
                    style="width:100%"
                    v-model="state.ruleForm.validStart"
                    type="date"
                    format="yyyy-MM-dd"
                    value-format="yyyy-MM-dd"
                    placeholder="有效期起"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
              <el-form-item label="有效期止">
                <el-date-picker style="width:100%" v-model="state.ruleForm.validEnd" type="date"
                                format="yyyy-MM-dd"
                                value-format="yyyy-MM-dd" placeholder="有效期止" clearable></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="35">
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
              <el-form-item label="运输企业">
                <el-input v-model="state.ruleForm.transportCompany" placeholder="运输企业" clearable></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="35">
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
              <el-form-item label="途经地">
                <el-input v-model="state.ruleForm.viaLocation" placeholder="途经地" clearable></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="35">
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
              <el-form-item label="标志牌顺序号">
                <el-input v-model="state.ruleForm.signSerialNumber" placeholder="标志牌顺序号" clearable></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="35">
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
              <el-form-item label="企业签发人">
                <el-input v-model="state.ruleForm.reserved1" placeholder="企业签发人" clearable></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template>
					<span class="dialog-footer">
						<el-button @click="onCancel" size="default">取 消</el-button>
						<el-button type="primary" @click="onSubmit" :loading="state.submitBtn.loading"
                       size="default">{{ state.dialog.submitTxt }}</el-button>
					</span>
        </template>
      </div>
    </el-dialog>

    <!-- 二维码弹窗 -->
    <el-dialog
        title="包车标志牌信息"
        :visible.sync="qrDialogVisible"
        width="20%"
        center
    >
      <div class="qr-code-container">
        <img :src="qrCodeUrl" alt="人员二维码" class="qr-code-image">
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { useBusApi } from '@/api/bus';
import { Message, MessageBox } from 'element-ui';
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';

export default {
  name: "bus",
  data() {
    return {
      pdfData: {
        signSerialNumber: '',
        startLocation: '',
        endLocation: '',
        viaLocation: '',
        vehicleNumber: '',
        driverName: '',
        transportCompany: '',
        reserved1: '',
        validStart: '',
        validEnd: '',
        qrCode: ''
      },
      state: {
        tableData: {
          data: [],
          total: 0,
          loading: false,
          param: {
            current: 1,
            limit: 10,
            keyword: '',
          }
        },
        dialog: {
          isShowDialog: false,
          type: '',
          title: '',
          submitTxt: '',
        },
        ruleForm: {
          driverName: '', // 驾驶员
          endLocation: '', // 终到地
          signSerialNumber: '', // 标志牌顺序号
          startLocation: '', // 起始地
          transportCompany: '', // 运输企业
          validEnd: '', // 有效期止
          validStart: '', // 有效期起
          vehicleColor: '', // 车辆号牌颜色
          vehicleNumber: '', // 车辆号牌
          viaLocation: '', // 途经地
          reserved1: '', // 企业签发人
        },
        submitBtn: {
          loading: false,
          type: ''
        },
      },
      qrDialogVisible: false,
      qrCodeUrl: '',
      loading: false,
      currentRowData: null
    }
  },
  methods: {
    // 表格日期格式化（仅显示年月日）
    dateFormatter(row, column, cellValue) {
      if (!cellValue) return '';
      return cellValue.slice(0, 10); // 仅在表格显示时截断，不修改原始数据
    },
    fetchData() {
      this.state.ruleForm = {}
      this.state.tableData.loading = true
      useBusApi().list(this.state.tableData.param).then(response => {
        this.state.tableData.data = response.data.records; // 保留完整日期时间
        this.state.tableData.total = response.data.total;
        this.state.tableData.loading = false;
      })
    },
    onOpenAddOrEdit(type, row) {
      if (type === 'edit') {
        this.state.submitBtn.type = 'edit';
        // 处理日期显示，仅保留年月日部分
        this.state.ruleForm = {
          ...row,
          validStart: row.validStart ? row.validStart.split(' ')[0] : '',
          validEnd: row.validEnd ? row.validEnd.split(' ')[0] : ''
        };
        this.state.dialog.title = '修改包车备案信息';
        this.state.dialog.submitTxt = '修 改';
      } else {
        this.state.submitBtn.type = 'add';
        this.state.ruleForm = {
          driverName: '', // 驾驶员
          endLocation: '', // 终到地
          signSerialNumber: '', // 标志牌顺序号
          startLocation: '', // 起始地
          transportCompany: '', // 运输企业
          validEnd: '', // 有效期止
          validStart: '', // 有效期起
          // vehicleColor: '', // 车辆号牌颜色
          vehicleNumber: '', // 车辆号牌
          viaLocation: '', // 途经地
        };
        this.state.dialog.title = '新增包车备案信息';
        this.state.dialog.submitTxt = '新 增';
      }
      this.state.dialog.isShowDialog = true;
    },
    onRowDel(row) {
      MessageBox.confirm(`此操作将永久删除，是否继续?`, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.deleteInfo(row)
      }).catch(() => {
      });
    },
    handleSizeChange(pageSize) {
      this.state.tableData.data = []
      this.state.tableData.param.limit = pageSize
      this.fetchData()
    },
    handleCurrentChange(current) {
      this.state.tableData.data = []
      this.state.tableData.param.current = current
      this.fetchData()
    },
    closeDialog() {
      this.state.dialog.isShowDialog = false;
    },
    onCancel() {
      this.closeDialog();
    },
    onSubmit() {
      this.state.submitBtn.loading = true;
      // 处理日期时间，添加默认时分秒
      const formData = {
        ...this.state.ruleForm,
        validStart: this.state.ruleForm.validStart ? `${this.state.ruleForm.validStart} 00:00:00` : '',
        validEnd: this.state.ruleForm.validEnd ? `${this.state.ruleForm.validEnd} 00:00:00` : ''
      };
      if (this.state.submitBtn.type === 'edit') {
        useBusApi().update(formData).then(response => {
          this.state.submitBtn.loading = false;
          this.closeDialog();
          this.fetchData()
        }).catch(() => {
          this.state.submitBtn.loading = false
        })
      } else {
        useBusApi().add(formData).then(response => {
          this.state.submitBtn.loading = false;
          this.closeDialog();
          this.fetchData()
        }).catch(() => {
          this.state.submitBtn.loading = false
        })
      }
    },
    getQrCodeUrl(formData) {  // 接收表单数据参数
      console.log('二维码---', formData);
      this.loading = true;
      useBusApi().generateQrCode(formData)  // 使用传入的表单数据
          .then(res => {
            console.log('二维码接口响应:', res);
            if (res.code === 0 && typeof res.qrCode === 'string') {
              this.qrCodeUrl = res.qrCode;
              this.qrDialogVisible = true;
              this.$message.success('二维码生成成功');
            } else {
              this.$message.error(`生成二维码失败: ${res.msg || '未获取到有效图片数据'}`);
            }
          })
          .catch(error => {
            console.error('生成二维码接口异常:', error);
            this.$message.error('网络错误，无法生成二维码');
          })
          .finally(() => {
            this.loading = false;
          });
    },
    getQrCodeUrlSee(formData) {  // 接收表单数据参数
      console.log('二维码---', formData);
      this.loading = true;
      useBusApi().generateQrCode(formData)  // 使用传入的表单数据
          .then(res => {
            console.log('二维码接口响应:', res);
            if (res.code === 0 && typeof res.qrCode === 'string') {
              this.qrCodeUrl = res.qrCode;
              this.qrDialogVisible = true;
            } else {
              this.$message.error(`查看二维码失败: ${res.msg || '未获取到有效图片数据'}`);
            }
          })
          .catch(error => {
            console.error('查看二维码接口异常:', error);
            this.$message.error('网络错误，无法查看二维码');
          })
          .finally(() => {
            this.loading = false;
          });
    },
    deleteInfo(row) {
      useBusApi().delete(row).then(response => {
        Message.success('删除成功');
        this.fetchData()
      }).catch(() => {
        this.fetchData()
      })
    },
    // // 新增：移除外部字体链接
    // removeExternalFonts() {
    //   const links = document.getElementsByTagName('link');
    //   Array.from(links).forEach(link => {
    //     if (link.href.includes('netdna.bootstrapcdn.com') || link.href.includes('font-awesome')) {
    //       link.remove();
    //       console.log('已移除外部字体链接:', link.href);
    //     }
    //   });
    // },
    //
    // // 新增：阻止外部资源请求
    // blockExternalResources() {
    //   const originalFetch = window.fetch;
    //   window.fetch = function(url, options) {
    //     if (url.includes('font-awesome') || url.includes('netdna.bootstrapcdn.com')) {
    //       console.log('已阻止外部资源请求:', url);
    //       return Promise.resolve(new Response(JSON.stringify({}), { status: 200 }));
    //     }
    //     return originalFetch.apply(this, arguments);
    //   };
    // },
    /**
     * 格式化有效期（仅保留日期部分）
     */
    formatValidDate(dateStr) {
      if (!dateStr) return '';
      // 提取日期部分（YYYY-MM-DD）
      return dateStr.split(' ')[0];
    },

    /**
     * 下载PDF文件（格式修复版）
     */
    downloadPDF(row) {
      this.pdfData = { ...row, qrCode: '' };

      // 获取二维码
      useBusApi().generateQrCode(row)
          .then(res => {
            if (res.code === 0 && res.qrCode) {
              this.pdfData.qrCode = res.qrCode;
              this.$nextTick(() => this.generatePdf(row.signSerialNumber));
            } else {
              Message.error('获取二维码失败');
              this.loading = false;
            }
          })
          .catch(error => {
            console.error('包车凭证下载失败:', error);
            Message.error('包车凭证下载失败，请重试');
            this.loading = false;
          });
    },

    /**
     * 填充PDF模板数据
     */
    fillPdfTemplate(row, qrCode) {
      document.getElementById('pdf-signSerialNumber').textContent = row.signSerialNumber || '';
      document.getElementById('pdf-startLocation').textContent = row.startLocation || '';
      document.getElementById('pdf-endLocation').textContent = row.endLocation || '';
      document.getElementById('pdf-viaLocation').textContent = row.viaLocation || '';
      document.getElementById('pdf-vehicleNumber').textContent = row.vehicleNumber || '';
      document.getElementById('pdf-driverName').textContent = row.driverName || '';
      document.getElementById('pdf-transportCompany').textContent = row.transportCompany || '';
      document.getElementById('pdf-reserved1').textContent = row.reserved1 || '';
      document.getElementById('pdf-validStart').textContent = this.dateFormatter(null, null, row.validStart);
      document.getElementById('pdf-validEnd').textContent = this.dateFormatter(null, null, row.validEnd);

      // 设置二维码
      const qrImg = document.getElementById('pdf-qrcode');
      qrImg.src = qrCode;
    },

    /**
     * 生成PDF文件（格式修复版）
     */
    generatePdf(fileName) {
      const pdfTemplate = document.getElementById('pdf-template');
      this.loading = true;
      html2canvas(pdfTemplate, {
        useCORS: true,
        scale: 2,
        dpi: 300,
        logging: false,
        timeout: 15000
      }).then(canvas => {
        try {
          const pdf = new jsPDF('p', 'mm', 'a4');
          const imgData = canvas.toDataURL('image/jpeg', 0.95);
          pdf.addImage(imgData, 'JPEG', 0, 0, 210, 297);
          pdf.save(`包车凭证_${fileName}.pdf`);

          this.loading = false;
          Message.success('包车凭证下载成功');
        } catch (error) {
          console.error('包车凭证下载错误:', error);
          Message.error('包车凭证下载失败');
          this.loading = false;
        }
      });
    }
  },
  computed: {},
  created() {

  },
  mounted() {
    this.fetchData()
  }
}
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

#font-size {
  font-size: 18px;
}

#pdf-template {
  position: relative;
  width: 210mm;
  height: 297mm;
  padding: 20px;
  background-color: white;
  /* 使用系统默认字体 */
  font-family: 'SimSun', '宋体', serif !important;
}
#title {
  /* 使用系统默认字体 */
  font-family: "SimHei", "Microsoft YaHei", Arial, sans-serif;
}
.qr-code-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
}

.qr-code-image {
  width: 400px;
  height: 400px;
}
/* 边框样式保留 */
.outer-border {
  border: 3px solid #000 !important;
  padding: 5px !important;
  height: 100% !important;
  box-sizing: border-box !important;
}

.inner-border {
  border: 1px solid #000 !important;
  padding: 35px !important;
  height: 100% !important;
  box-sizing: border-box !important;
}
</style>
